# import os

# # def compare_folders(folder1, folder2):
# #     """比较两个文件夹中的文件是否一一对应，并输出统计信息"""
# #     # 获取两个文件夹中的所有文件名
# #     folder1_files = [f for f in os.listdir(folder1) if os.path.isfile(os.path.join(folder1, f))]
# #     folder2_files = [f for f in os.listdir(folder2) if os.path.isfile(os.path.join(folder2, f))]
    
# #     # 创建字典存储基础文件名
# #     base_names = {}
# #     unmatched_in_folder1 = []
# #     matched_pairs = []
# #     matched_in_folder2 = set()
    
# #     # 为folder2创建基础文件名字典
# #     for file2 in folder2_files:
# #         base_name = os.path.splitext(file2)[0]  # 去除扩展名
# #         base_names[base_name] = file2
    
# #     # 检查folder1中的文件是否在folder2中有对应
# #     for file1 in folder1_files:
# #         # 提取基础部分（去除后缀和扩展名）
# #         base_part = file1.rsplit('_', 1)[0] if '_' in file1 else os.path.splitext(file1)[0]
        
# #         if base_part in base_names:
# #             matched_pairs.append((file1, base_names[base_part]))
# #             matched_in_folder2.add(base_names[base_part])
# #         else:
# #             unmatched_in_folder1.append(file1)
    
# #     # 找出folder2中未匹配的文件
# #     unmatched_in_folder2 = [file for file in folder2_files if file not in matched_in_folder2]
    
# #     # 返回统计结果
# #     return {
# #         "folder1_count": len(folder1_files),
# #         "folder2_count": len(folder2_files),
# #         "matched_count": len(matched_pairs),
# #         "unmatched_in_folder1": unmatched_in_folder1,
# #         "unmatched_in_folder2": unmatched_in_folder2,
# #         "matched_pairs": matched_pairs
# #     }

# def compare_folders(folder1, folder2):
#     """比较两个文件夹中的文件是否一一对应"""
#     # 获取两个文件夹中的所有文件名
#     folder1_files = [f for f in os.listdir(folder1) if os.path.isfile(os.path.join(folder1, f))]
#     folder2_files = [f for f in os.listdir(folder2) if os.path.isfile(os.path.join(folder2, f))]
    
#     # 创建字典存储基础文件名
#     base_names = {}
#     unmatched_in_folder1 = []
#     matched_pairs = []
#     matched_in_folder2 = set()
    
#     # 为folder2创建基础文件名字典（仅去除扩展名）
#     for file2 in folder2_files:
#         base_name = os.path.splitext(file2)[0]  # 仅去除扩展名
#         base_names[base_name] = file2
    
#     # 检查folder1中的文件是否在folder2中有对应
#     for file1 in folder1_files:
#         # 提取基础部分（去除扩展名）
#         base_without_ext = os.path.splitext(file1)[0]
        
#         # 分割文件名并去除最后两部分
#         parts = base_without_ext.split('_')
#         if len(parts) > 2:
#             base_part = '_'.join(parts[:-2])
#         else:
#             # 如果文件名中下划线不足两个，则使用整个文件名（不含扩展名）
#             base_part = base_without_ext
        
#         # 在folder2中查找匹配
#         if base_part in base_names:
#             matched_pairs.append((file1, base_names[base_part]))
#             matched_in_folder2.add(base_names[base_part])
#         else:
#             unmatched_in_folder1.append(file1)
    
#     # 找出folder2中未匹配的文件
#     unmatched_in_folder2 = [file for file in folder2_files if file not in matched_in_folder2]
    
#     # 返回统计结果
#     return {
#         "folder1_count": len(folder1_files),
#         "folder2_count": len(folder2_files),
#         "matched_count": len(matched_pairs),
#         "unmatched_in_folder1": unmatched_in_folder1,
#         "unmatched_in_folder2": unmatched_in_folder2,
#         "matched_pairs": matched_pairs
#     }

# def main():
#     # 输入文件夹路径
#     folder1 = r"F:\ADNI\ADNI_PNG_3Ddata\download_data\NIFTI_data\usefuldata\duodehaima\train\AD"
#     folder2 = r"F:\ADNI\ADNI_PNG_3Ddata\download_data\NIFTI_data\usefuldata\duodequannao\train\AD"
    
#     # 验证文件夹是否存在
#     if not os.path.isdir(folder1):
#         print(f"错误: 文件夹 '{folder1}' 不存在")
#         return
#     if not os.path.isdir(folder2):
#         print(f"错误: 文件夹 '{folder2}' 不存在")
#         return
    
#     # 执行比较
#     results = compare_folders(folder1, folder2)
    
#     # 输出结果
#     print("\n" + "="*50)
#     print(f"第一个文件夹样本数: {results['folder1_count']}")
#     print(f"第二个文件夹样本数: {results['folder2_count']}")
#     print(f"匹配的文件数: {results['matched_count']}")
#     print("\n" + "-"*50)
    
#     if results['unmatched_in_folder1']:
#         print("\n第一个文件夹中未匹配的文件:")
#         for file in results['unmatched_in_folder1']:
#             print(f"  - {file}")
#     else:
#         print("\n第一个文件夹中所有文件都找到了匹配")
    
#     if results['unmatched_in_folder2']:
#         print("\n第二个文件夹中未被匹配的文件:")
#         for file in results['unmatched_in_folder2']:
#             print(f"  - {file}")
#     else:
#         print("\n第二个文件夹中所有文件都被匹配")
    
#     # 可选择是否显示匹配详情
#     if results['matched_pairs'] and input("\n是否显示匹配详情? (y/n): ").lower() == 'y':
#         print("\n匹配的文件对:")
#         for pair in results['matched_pairs']:
#             print(f"  - {pair[0]} -> {pair[1]}")

# if __name__ == "__main__":
#     main()

import os

def get_core_name_folder1(filename):
    """
    去除 _L_Hipp.nii.gz 或 _R_Hipp.nii.gz 这种后缀，提取前缀部分
    """
    if filename.endswith('_L_Hipp.nii.gz'):
        return filename[:-len('_L_Hipp.nii.gz')]
    elif filename.endswith('_R_Hipp.nii.gz'):
        return filename[:-len('_R_Hipp.nii.gz')]
    else:
        # 其他不规则情况统一去掉 .nii
        return filename[:-len('.nii.gz')] if filename.endswith('.nii.gz') else filename

def get_core_name_folder2(filename):
    """
    去除 .nii.gz 后缀，提取前缀部分
    """
    return filename[:-len('.nii.gz')] if filename.endswith('.nii.gz') else filename

def check_folders(folder1, folder2):
    files1 = [f for f in os.listdir(folder1)]
    files2 = [f for f in os.listdir(folder2)]

    print(files1[:2])

    for i in range(3):
        print(files1[i])
        print(files2[i])
        print('\n')

    core_set2 = [get_core_name_folder2(f) for f in files2]
    core_set1 = [get_core_name_folder1(f) for f in files1]

    for i in range(3):
        print(core_set1[i])
        print(core_set2[i])
        print('\n')

    c1_unget = []
    c1_get = []

    c2_unget = []
    c2_get = []

    for i in core_set2:
        if i in core_set1:
            c1_get.append(i)
        else:
            c1_unget.append(i)
    
    for i in core_set1:
        if i in core_set2:
            c2_get.append(i)
        else:
            c2_unget.append(i)


    print(f"文件夹1样本数: {len(files1)}")
    print(f"文件夹2样本数: {len(files2)}")
    print(f"文件夹1匹配文件数: {len(c1_get)}")
    print(f"文件夹2匹配文件数: {len(c2_get)}")
    # print("文件夹1未匹配文件如下:")
    # for fname in c1_unget:
    #     print(f"  {fname}")
    # print("文件夹2未匹配文件如下:")
    # for fname in c2_unget:
    #     print(f"  {fname}")

if __name__ == '__main__':
    folder1 = r"F:\ADNI\ADNI_PNG_3Ddata\download_data\NIFTI_data\usefuldata\duodehaima\train\MCI"
    folder2 = r"F:\ADNI\ADNI_PNG_3Ddata\download_data\NIFTI_data\usefuldata\duodequannao\train\MCI"
    check_folders(folder1, folder2)
